<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<form>
	canme:<input type="text" name="cname"/><br/>
	sal:<input type="number" name="sal"/><br/>
	brith:<input type="date" name="birth"/><br/>
	<input type="radio" name="sex" value="true" checked="checked"/>男
	<input type="radio" name="sex" value="false"/>女<br/>
	<button>add</button>
</form>




<table id="customers"></table>



<script type="text/javascript">
(function(){
	var obj={};
	obj.ajax=function(type,url,data,headers,context,callback){
		$.ajax({type:type,url:url,data:JSON.stringify(data),headers:headers,context:context})
		.done(callback);
	};
	window.j=obj;
})();

function CustomersComponent(template){
	this.model=null;
	this.template=template;
	this.addCustomer=function(customer){
		j.ajax("POST","addCustomer",customer,{"Content-Type":"application/json"},this,function(customer){
			this.model.push(customer);
			_render(this.model);
		});
	};
	this.updateCustomer=function(customer){
		
	};
	this.findAllCustomers=function(){
		j.ajax("GET","findAllCustomers",null,null,this,function(customers){
			this.model=customers;
			_render(this.model);
		});
		
	};
	function _render(data){
		template.empty();
		data.forEach(function(item){
			$("<tr/>").append($("<td/>").text(item.id))
			.append($("<td/>").text(item.cname))
			.append($("<td/>").append($("<button/>").text("del").addClass("btn").data(item)))
			.appendTo(template);
		});
		$("button:contains(del)").on("click",function(){
			$this=$(this);
			j.ajax("DELETE","deleteCustomer?id="+$this.data().id,null,null,this,function(m){
				data=data.filter(function(item){
					return item.id!=$this.data().id;
				});
				_render(data);
			});
			
		});
		
	}
	
}


$(function(){
	var c=new CustomersComponent($("#customers"));
	c.findAllCustomers();
	$("button","form").on("click",function(e){
		var cname=$("input[name=cname]").val();
		var sal=$("input[name=sal]").val();
		var birth=$("input[name=birth]").val();
		var sex=$("input[name=sex]:checked").val();
		var c1={cname:cname,sex:sex,birth:birth,sal:sal};
		c.addCustomer(c1);
		e.preventDefault();
	})
	
	
	
	
	
	
})
	
</script>
</body>
</html>